/*
校验数据类型
示例：
typeOf('树哥')  // string
typeOf([])  // array
typeOf(new Date())  // date
typeOf(null) // null
typeOf(true) // boolean
typeOf(() => { }) // function
 */
export const typeOf = function (obj: any) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};

/*
防抖
示例：
methods: {
  loadList() {
    debounce(() => {
      console.log('加载数据')
    }, 500)
  }
}
 */
export const debounce = (() => {
  let timer: number | null | undefined = null;
  return (callback: TimerHandler, wait = 800) => {
    timer && clearTimeout(timer);
    timer = setTimeout(callback, wait);
  };
})();

/*
节流
 */
export const throttle = (() => {
  let last = 0;
  return (callback: () => void, wait = 800) => {
    let now = +new Date();
    if (now - last > wait) {
      callback();
      last = now;
    }
  };
})();
/*
手机号脱敏
 */
export const hideMobile = (mobile: string) => {
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
};

/*
开启全屏
 */
export const launchFullscreen = (element: {
  requestFullscreen: () => void;
  mozRequestFullScreen: () => void;
  msRequestFullscreen: () => void;
  webkitRequestFullscreen: any;
  webkitRequestFullScreen: () => void;
}) => {
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen();
  }
};
/*
退出全屏
 */
export const exitFullscreen = () => {
  if (document.exitFullscreen) {
    document.exitFullscreen();
    // @ts-ignore
  } else if (document.msExitFullscreen) {
    // @ts-ignore
    document.msExitFullscreen();
    // @ts-ignore
  } else if (document.mozCancelFullScreen) {
    // @ts-ignore
    document.mozCancelFullScreen();
    // @ts-ignore
  } else if (document.webkitExitFullscreen) {
    // @ts-ignore
    document.webkitExitFullscreen();
  }
};

/*
大小写转换
str 待转换的字符串
type 1-全大写 2-全小写 3-首字母大写
示例：
turnCase('vue', 1) // VUE
turnCase('REACT', 2) // react
turnCase('vue', 3) // Vue
 */
export const turnCase = (str: string, type: any) => {
  switch (type) {
    case 1:
      return str.toUpperCase();
    case 2:
      return str.toLowerCase();
    case 3:
      //return str[0].toUpperCase() + str.substr(1).toLowerCase() // substr 已不推荐使用
      return str[0].toUpperCase() + str.substring(1).toLowerCase();
    default:
      return str;
  }
};
/*
解析URL参数
示例：
// 假设目前位于 https://****com/index?id=154513&age=18;
getSearchParams(); // {id: "154513", age: "18"}
 */
export const getSearchParams = () => {
  const searchPar = new URLSearchParams(window.location.search);
  const paramsObj = {};
  // @ts-ignore
  for (const [key, value] of searchPar.entries()) {
    // @ts-ignore
    paramsObj[key] = value;
  }
  return paramsObj;
};

/**
 * 1: ios
 * 2: android
 * 3: 其它
 */
export const getOSType = () => {
  let u = navigator.userAgent,
    app = navigator.appVersion;
  let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
  let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  if (isIOS) {
    return 1;
  }
  if (isAndroid) {
    return 2;
  }
  return 3;
};

/*
数组对象根据字段去重
arr 要去重的数组
key 根据去重的字段名
示例：
const responseList = [
    { id: 1, name: '树哥' },
    { id: 2, name: '黄老爷' },
    { id: 3, name: '张麻子' },
    { id: 1, name: '黄老爷' },
    { id: 2, name: '张麻子' },
    { id: 3, name: '树哥' },
    { id: 1, name: '树哥' },
    { id: 2, name: '黄老爷' },
    { id: 3, name: '张麻子' },
]

uniqueArrayObject(responseList, 'id')
// [{ id: 1, name: '树哥' },{ id: 2, name: '黄老爷' },{ id: 3, name: '张麻子' }]
 */
export const uniqueArrayObject = (arr = [], key = 'id') => {
  if (arr.length === 0) return;
  let list = [];
  const map = {};
  arr.forEach((item) => {
    if (!map[item[key]]) {
      map[item[key]] = item;
    }
  });
  list = Object.values(map);

  return list;
};

/*
滚动到页面顶部
 */
export const scrollToTop = () => {
  const height = document.documentElement.scrollTop || document.body.scrollTop;
  if (height > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, height - height / 8);
  }
};
/*
滚动到元素位置
smoothScroll('#target'); // 平滑滚动到 ID 为 target 的元素
 */
export const smoothScroll = (element: any) => {
  document.querySelector(element).scrollIntoView({
    behavior: 'smooth',
  });
};

export const uuid = () => {
  const temp_url = URL.createObjectURL(new Blob());
  const uuid = temp_url.toString();
  URL.revokeObjectURL(temp_url); //释放这个url
  return uuid.substring(uuid.lastIndexOf('/') + 1);
};
/*
金额格式化
示例：
{number} number：要格式化的数字
{number} decimals：保留几位小数
{string} dec_point：小数点符号
{string} thousands_sep：千分位符号
示例：
moneyFormat(10000000) // 10,000,000.00
moneyFormat(10000000, 3, '.', '-') // 10-000-000.000
 */
// @ts-ignore
export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '');
  const n = !isFinite(+number) ? 0 : +number;
  const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals);
  const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep;
  const dec = typeof dec_point === 'undefined' ? '.' : dec_point;
  let s: string[] = [];
  // @ts-ignore
  const toFixedFix = function (n, prec) {
    const k = Math.pow(10, prec);
    return '' + Math.ceil(n * k) / k;
  };
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  const re = /(-?\d+)(\d{3})/;
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2');
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
};

export const px2rpx = (px: number) => {
  const windowWidth = uni.getSystemInfoSync().windowWidth;
  return px * (750 / windowWidth);
};
export const rpxTopx = (rpx: number) => {
  const windowWidth = uni.getSystemInfoSync().windowWidth;
  return (windowWidth * rpx) / 750;
};

// 设置入组率
export function setSubjectGroupPercentage(num: number) {
  if (num === 0) return 0;
  if (num < 1) return 1;
  return Math.floor(num);
}

// 获取APP信息
export const getAppInfo = (appList: any) => {
  const appData = appList.find((item: any) => item.appCode === 'CTMS');
  if (appData) {
    return appData;
  } else {
    throw new Error('getAppInfo 没有找到应用信息');
  }
};

// type last 最后一个， first 第一个
export const getNameShort = (name: string, type: string): string => {
  if (!name) {
    return '';
  }
  const arr = name.split('');
  if (type === 'first') {
    return arr[0];
  }
  return arr[arr.length - 1];
};

// 把常量数组转换成{value:label}
export function APPFN_SET_VALUE_LABEL(arr: any[]) {
  const obj: any = {};
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    obj[item.value] = item.label;
  }
  return obj;
}

// 把常量数组转换成Map
export function APPFN_SET_VALUE_MAP(arr: any[]) {
  const obj: any = {};
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    obj[item.value] = item;
  }
  return obj;
}
// 日期格式化
export function dataFormat(fmt: string, dt?: any) {
  !fmt && (fmt = 'yyyy/MM/dd');
  !dt && (dt = new Date());
  let ret;
  const opt: any = {
    'Y+': dt.getFullYear().toString(), // 年
    'y+': dt.getFullYear().toString(), // 年
    'M+': (dt.getMonth() + 1).toString(), // 月
    'd+': dt.getDate().toString(), // 日
    'D+': dt.getDate().toString(), // 日
    'H+': dt.getHours().toString(), // 时
    'h+': dt.getHours().toString(), // 时
    'm+': dt.getMinutes().toString(), // 分
    'S+': dt.getSeconds().toString(), // 秒
    's+': dt.getSeconds().toString(), // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (const k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
      );
    }
  }
  return fmt;
}
/**
 * 获取数据类型
 * @param {} obj
 * @return boolean | number | string | function | array | date | regExp | undefined | null | object
 */
export function getType(obj: any) {
  const toString = Object.prototype.toString;
  const map: any = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
  };
  return map[toString.call(obj)];
}
/**
 * 格式化金额
 */
export function formatPrice(price: any) {
  if (getType(price) !== 'number') {
    return price;
    // throw new Error('金额非数字，无法转换')
  }
  price = price.toString().replace(/\$|\,/g, '');
  if (isNaN(price)) price = '0';
  const sign = price == (price = Math.abs(price));
  price = Math.floor(price * 100 + 0.50000000001);
  let cents: any = price % 100;
  price = Math.floor(price / 100).toString();
  if (cents < 10) cents = '0' + cents;
  for (var i = 0; i < Math.floor((price.length - (1 + i)) / 3); i++)
    price =
      price.substring(0, price.length - (4 * i + 3)) +
      ',' +
      price.substring(price.length - (4 * i + 3));
  return (sign ? '￥' : '-￥') + price + '.' + cents;
}
